package com.orhon.smartcampus.modules.user.mutation;


import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.SchoolsDao;
import com.orhon.smartcampus.modules.base.entity.Schools;
import com.orhon.smartcampus.modules.user.dao.UsersDao;
import com.orhon.smartcampus.modules.user.entity.Users;
import com.orhon.smartcampus.modules.user.gqlInputModel.GQLUserInput;
import com.orhon.smartcampus.modules.user.inputMapper.UserInputMapper;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Component
public class UpdateUserPasswordMutation implements DataFetcher {

    @Autowired
    UsersDao usersDao;

    @Override
    @Transactional(readOnly = false)
    public Object get(DataFetchingEnvironment env) throws Exception {

//        GQLUserInput input = UserInputMapper.MAPPER.mapInput(env.getArgument("inputData"));

        String username = env.getArgument("username");
//        String username = input.getUsername();
        String password = env.getArgument("password");
//        String password = input.getUsername();

        System.out.println(username);

        String chek_sql = "(username = '" + username +"' or mobile = '"+ username +"' or idcard = '" + username + "')";
        String hql = "from Users where deleted_at = null and " + chek_sql;

        Users users =  usersDao.findId(hql, null);
//        Users users =  usersDao.get(Users.class, input.getId());
        users.setUpdated_at(new Date());
//        if(input.getPassword() != null){
        if(password != null){
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//            String encode = bCryptPasswordEncoder.encode(input.getPassword());
            String encode = bCryptPasswordEncoder.encode(password);
            String s = convertJavaBcryptPassword(encode);
            users.setPassword(encode);
        }

        try {
            usersDao.saveOrUpdate(users);
        } catch (Exception e) {
            return Result.error(500,""+e);
        }
        return Result.ok();
    }

    private String convertJavaBcryptPassword(String oldPass) {
        String old_password = oldPass;
        String new_password = "";
        if (old_password.charAt(2) == 'a') {
            StringBuilder strBuilder = new StringBuilder(old_password);
            strBuilder.setCharAt(2, 'y');
            new_password = strBuilder.toString();
            return new_password;
        } else {
            return old_password;
        }
    }
}
